package com.run.go.gearbox.mysql.handler;

import com.run.go.gearbox.mysql.MysqlTransmission;
import com.run.go.gearbox.mysql.codec.MySqlDecoder;
import com.run.go.gearbox.mysql.codec.NettyMysqlDecoder;
import com.run.go.gearbox.mysql.codec.parse.Connected;
import com.run.go.gearbox.mysql.codec.parse.Connecting;
import com.run.go.gearbox.mysql.request.LoginRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;

public class MysqlNettyOutHandler extends ChannelOutboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(MysqlNettyOutHandler.class);

    public final String DECODER = MysqlTransmission.class.getName() + ".decoder";


    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        logger.info("连接mysql");
        /* 登录认证 */
        ctx.channel().pipeline().addFirst(DECODER, new NettyMysqlDecoder(new MySqlDecoder(new Connecting())));
        super.connect(ctx, remoteAddress, localAddress, promise);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof LoginRequest){
            /* 登录完成解码 */
            ctx.channel().pipeline().remove(DECODER);
            ctx.channel().pipeline().addFirst(DECODER, new NettyMysqlDecoder(new MySqlDecoder(new Connected())));
        }
        super.write(ctx, msg, promise);
    }
}
